package com.lvcoding.secdemo1.security;

import com.lvcoding.secdemo1.exception.KaptchaNotMatchException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class KaptchaFilter extends UsernamePasswordAuthenticationFilter {

	private static final String SPRING_SECURITY_FORM_KAPTCHA_KEY = "kaptcha";

	private String kaptchaParameter = SPRING_SECURITY_FORM_KAPTCHA_KEY;

	// @Autowired
	// public KaptchaFilter(@Lazy AuthenticationManager authenticationManager) {
	// setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/doLogin",
	// HttpMethod.POST.name()));
	// setAuthenticationManager(authenticationManager);
	// }

	public String getKaptchaParameter() {
		return kaptchaParameter;
	}

	public void setKaptchaParameter(String kaptchaParameter) {
		this.kaptchaParameter = kaptchaParameter;
	}

	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws AuthenticationException {
		if (!request.getMethod().equals("POST")) {
			throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
		}

		String kaptchaSession = (String) request.getSession().getAttribute(getKaptchaParameter());
		String kaptchaForm = request.getParameter(getKaptchaParameter());

		if (ObjectUtils.isEmpty(kaptchaForm) || !kaptchaForm.equalsIgnoreCase(kaptchaSession)) {
			throw new KaptchaNotMatchException("验证码不正确");
		}

		return super.attemptAuthentication(request, response);
	}

	// @Autowired
	// @Override
	// public void setAuthenticationManager(AuthenticationManager authenticationManager) {
	// super.setAuthenticationManager(authenticationManager);
	// }

}
